package me.chan.chatting.server.service.impl;

import io.netty.channel.Channel;
import me.chan.chatting.server.service.GroupService;
import me.chan.chatting.server.factory.SessionServiceFactory;
import me.chan.chatting.server.model.Group;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

public class GroupServiceImpl implements GroupService {

    private final Map<String, Group> groupMap = new ConcurrentHashMap<>();


    /**
     *
     * @param name
     * @param members
     * @return if the group is created successfully, then return the group
     *          otherwise it return null when the group is existed
     */
    @Override
    public Group createGroup(String name, Set<String> members) {
        Group group = new Group(name, members);
        Group g = groupMap.putIfAbsent(name, group);
        return Objects.isNull(g) ? group : null;
    }

    @Override
    public Group joinMember(String name, String member) {
        return groupMap.computeIfPresent(name, (key, value) -> {
            value.getMembers().add(member);
            return value;
        });
    }

    @Override
    public Group removeMember(String name, String member) {
        return groupMap.computeIfPresent(name, (gname, group) -> {
            group.getMembers().remove(member);
            return group;
        });
    }

    @Override
    public Group removeGroup(String name) {
        return groupMap.remove(name);
    }

    @Override
    public Set<String> getMembers(String name) {
        return groupMap.getOrDefault(name, Group.EMPTY_GROUP).getMembers();
    }

    @Override
    public List<Channel> getMembersChannel(String name) {
        return getMembers(name).stream()
                .map(member -> SessionServiceFactory.getInstance().getChannel(member))
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }
}
